#!/usr/bin/python
"""\
Examples
--------
* Print the second extension header for data.fits

fhdr -1 data.fits

* Print the headers for all extensions for data.fits

fhdr -all data1.fits

* List the first headers of data1.fits and data2.fits, and grab any
  lines that have 'OBS' in them

fhdr data1.fits data2.fits | grep 'OBS'

* List the values of the NAXIS CD1_1 and OBID keywords for all the
  files ending in .fits in the current directory.

fhdr *.fits NAXIS CD1_1 OBSID
"""
import sys
import pyfits

usage = """\
Usage: fhdr -[extension number] filename(s) [keys]

[extension number] is the number of the fits extension to print the
header for. The first extension header (number 0) is shown by
default. '-all' prints all extension headers.

If any keys are given, then only those keys are printed.
"""

def main(args):
    all = False
    if args[0].startswith('-'):
        if args[0][1:] == 'all':
            all = True
        else:
            try:
                iext = int(args[0][1:])
            except ValueError:
                print usage
                sys.exit(1)
        args = args[1:]
    else:
        iext = 0

    filenames = []
    width = 0
    while args and '.' in args[0]:
        filename = args.pop(0)
        width = max(width, len(filename))
        filenames.append(filename)

    keys = args

    if not keys:
        for filename in filenames:
            fh = pyfits.open(filename)
            print '   Header for %s:' % filename
            if all:
                for hdu in fh:
                    print hdu.header
            else:
                print fh[iext].header
            fh.close()
    else:
        format = '  '.join(['%%-%is' % width] + ['%s'] * len(keys))
        print format % tuple(['FILENAME'] + keys)
        for filename in filenames:
            fh = pyfits.open(filename)
            out = [filename]
            for key in keys:
                hd = fh[iext].header
                try:
                    val = hd[key]
                except KeyError:
                    print  '\nHeader keyword %s not found in %s' % (
                        key, filename)
                    sys.exit(1)
                out.append(val)
            print format % tuple(out)

if __name__ =='__main__':
    if len(sys.argv) == 1:
        print usage
        sys.exit(1)        
    main(sys.argv[1:])
